<template>
    <div class="page-content">
        <div class="header">
            <h3>基础设置</h3>
        </div>
        <el-form label-width="120px" :model="formData" :rules="rules" ref="ruleFormRef">
            <el-form-item label="活动类型">
                <div class="tips">老带新活动</div>
            </el-form-item>
            <el-form-item label="活动名称" prop="activityName">
                <el-input v-model="formData.activityName" placeholder="请输入活动名称"></el-input>
            </el-form-item>
            <el-form-item label="活动时间" prop="activeTime">
                <el-date-picker label="活动时间：" v-model="formData.activeTime" type="datetimerange"
                    start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss"
                    date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" @change="timeChange" />
            </el-form-item>
            <!-- <el-form-item label="活动标题" prop="title">
                <el-input v-model="formData.title" maxlength="12" show-word-limit placeholder="请输入标题"></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="活动背景">
                <el-input v-model="formData.shareImage" style="display: none"></el-input>
                <div class="avatar-uploader" @click="openImageDialog('shareImage')">
                    <el-image v-if="formData.shareImage" :src="formData.shareImage" class="avatar"
                        fit="contain"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                            <Plus />
                        </el-icon></i>
                    <div v-if="formData.shareImage" class="mask">替换</div>
                    <el-icon v-if="formData.shareImage" class="del-image" :size="20"
                        @click.stop="handleDelImg('shareImage')">
                        <CircleCloseFilled />
                    </el-icon>
                </div>
            </el-form-item> -->
            <el-form-item label="邀请分享标题" prop="subtitle">
                <el-input v-model="formData.subtitle" maxlength="25" show-word-limit placeholder="请输入副标题"></el-input>
            </el-form-item>
            <el-form-item label="邀请分享图片">
                <el-input v-model="formData.receiveSuccessImage" style="display: none"></el-input>
                <div class="avatar-uploader" @click="openImageDialog('receiveSuccessImage')">
                    <el-image v-if="formData.receiveSuccessImage" :src="formData.receiveSuccessImage" class="avatar"
                        fit="contain"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                            <Plus />
                        </el-icon></i>
                    <div v-if="formData.receiveSuccessImage" class="mask">替换</div>
                    <el-icon v-if="formData.receiveSuccessImage" class="del-image" :size="20"
                        @click.stop="handleDelImg('receiveSuccessImage')">
                        <CircleCloseFilled />
                    </el-icon>
                </div>
            </el-form-item>
            <el-form-item label="活动状态" prop="status">
                <el-switch v-model="formData.status" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
        </el-form>
        <div class="header">
            <h3>活动规则</h3>
        </div>
        <el-form label-width="130px" :model="formData" :rules="rules" ref="ruleFormRef">
            <el-form-item label="活动说明">
                <div>
                    <div class="tips">活动时间内老用户邀请新用户</div>
                    <div class="coutomTips">新用户指的是未在平台注册过的手机号</div>
                </div>
            </el-form-item>
            <el-form-item label="老用户邀请赠送">
                <el-checkbox-group v-model="formData.activityContentVoList[0].targetUserType">
                    <el-checkbox value="01">赠送会员Vip</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="选择vip" v-if="formData.activityContentVoList[0].targetUserType.join() === '01'">
                <el-select v-model="formData.activityContentVoList[0].giftRefIds">
                    <el-option :label="item.name" :value="item.id" v-for="(item, index) in vipData" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="老用户额外赠送">
                <el-switch v-model="formData.state" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            <!-- 动态赠送规则列表 -->
            <div v-if="formData.state === 1">
                <div v-for="(rule, index) in formData.extraGiftRules" :key="index" class="giftRules">
                    <div class="rules">
                        <span style="font-weight: bold;color:#000;">赠送规则 {{ index + 1 }}</span>
                        <el-button type="danger" size="small" @click="removeGiftRule(index)">删除</el-button>
                    </div>
                    <el-form-item label="邀请人数">
                        <el-input v-model="rule.extraGiftRuleQuantity" placeholder="请输入邀请人数">
                            <template #append>人</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="选择vip">
                        <el-select v-model="rule.giftRefIds" placeholder="请选择VIP" style="width: 100%;">
                            <el-option :label="item.name" :value="item.id" v-for="(item, idx) in vipData" :key="idx" />
                        </el-select>
                    </el-form-item>
                </div>
            </div>
            <div class="addRules" v-if="formData.state === 1">
                <el-button type="primary" @click="addGiftRule" size="large">添加赠送规则</el-button>
            </div>
            <el-form-item label="被邀请新用户赠送">
                <el-checkbox-group v-model="formData.activityContentVoList[1].targetUserType">
                    <el-checkbox value="02">赠送会员Vip</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="选择vip" v-if="formData.activityContentVoList[1].targetUserType.join() === '02'">
                <el-select v-model="formData.activityContentVoList[1].giftRefIds">
                    <el-option :label="item.name" :value="item.id" v-for="(item, index) in vipData" :key="index" />
                </el-select>
            </el-form-item>
            <el-form-item label="规则说明">
                <ArtWangEditor v-model="formData.remark" />
            </el-form-item>
            <el-form-item>
                <!-- <el-button type="primary" style="width: 90px" v-if="!isEdit" @click="edit">
                    编辑
                </el-button> -->
                <el-button type="primary" style="width: 90px" @click="handleSave" :loading="btnLoding">
                    保存
                </el-button>
                <el-button type="default" @click="goBack">返回</el-button>
            </el-form-item>
        </el-form>
        <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
            :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
            :operationType="false"></image-selected-dialog>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import { addActive, getActivityInfo, editActive } from '@/api/marketing'
import { vipEquity } from '@/api/userStudentsApi'
import { useRoute } from 'vue-router'

const route = useRoute()

const formData = reactive({
    activityName: '',
    activeTime: ['', ''],
    startTime: '',
    endTime: '',
    shareImage: '',
    receiveSuccessImage: '',
    // oldUserGiftType: ['1'],
    // newUserGiftType: ['1'],
    status: 1,
    title: '',
    subtitle: '',
    remark: '',
    activityContentVoList: [
        {
            targetType: '01',
            giftType: '04',
            // giftRefIds: [],
            giftRefIds: '',
            targetUserType: ['01'],
            giftQuantity: 1,
            limitPerUser: 1,
            extraGiftRuleQuantity: 0,
            extraGiftRuleType: '01'
        },
        {
            targetType: '01',
            giftType: '04',
            // giftRefIds: [],
            giftRefIds: '',
            targetUserType: ['02'],
            giftQuantity: 1,
            limitPerUser: 0,
            extraGiftRuleQuantity: 0,
            extraGiftRuleType: '01'
        }
    ],
    state: 1,
    extraGiftRules: [] as any[] // 额外的赠送规则列表
})

const router = useRouter()
const isEdit = ref(false)
const btnLoding = ref(false)

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
    activeTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
    title: [{ required: true, message: '请输入标题', trigger: 'change' }],
    subtitle: [{ required: true, message: '请输入副标题', trigger: 'change' },]
})
const timeChange = (e: any) => {
    formData.startTime = e[0]
    formData.endTime = e[1]
}

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const vipData = ref<any>([])
const currentImageType = ref('') // 当前操作的图片类型

const openImageDialog = (imageType: string) => {
    currentImageType.value = imageType
    showImageChooseDialog.value = true
}

const handleCloseImageDialog = (value: any) => {
    if (value && value.fileUrl) {
        if (currentImageType.value === 'shareImage') {
            formData.shareImage = value.fileUrl
        } else if (currentImageType.value === 'receiveSuccessImage') {
            formData.receiveSuccessImage = value.fileUrl
        }
    }
    showImageChooseDialog.value = false
    currentImageType.value = ''
}

const handleDelImg = (imageType: string) => {
    if (imageType === 'shareImage') {
        formData.shareImage = ''
    } else if (imageType === 'receiveSuccessImage') {
        formData.receiveSuccessImage = ''
    }
}

// 新增赠送规则
const addGiftRule = () => {
    if (formData.extraGiftRules.length > 2) {
        ElMessage.error('最多只能添加三个规则')
        return
    }
    formData.extraGiftRules.push({
        targetType: '01',
        giftType: '04',
        giftRefIds: '',
        targetUserType: '0101',
        giftQuantity: 1,
        limitPerUser: 0,
        extraGiftRuleQuantity: 0,
        extraGiftRuleType: '01'
    })
}

// 删除赠送规则
const removeGiftRule = (index: number) => {
    formData.extraGiftRules.splice(index, 1)
}
const edit = () => {
    isEdit.value = !isEdit.value
}

const formatDate = (date: string) => {
    return new Date(date)
        .toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        })
        .replace(/\//g, '-')
}

const editId = ref('')

const handleSave = () => {
    // isEdit.value = !isEdit.value
    // buildActivityObj()
    // return
    if (editId.value) {
        editHandle()
    } else {
        addHandle()
    }
}

function goBack() {
    router.push('/result/mentoringNewcomers')
}

const buildActivityObj = () => {
    //老用户额外赠送开关关闭
    if (formData.state === 0) {
        formData.extraGiftRules = []
    }
    const obj: any = {
        activityName: formData.activityName,
        shareImage: formData.shareImage,
        receiveSuccessImage: formData.receiveSuccessImage,
        startTime: formData.startTime ? formatDate(formData.startTime) : '',
        endTime: formData.endTime ? formatDate(formData.endTime) : '',
        activityType: '06',
        status: formData.status,
        title: formData.title,
        subtitle: formData.subtitle,
        activityContentVoList: formData.activityContentVoList.map((e: any) => {
            return {
                targetType: '01',
                giftType: '04',
                // giftRefIds: e.giftRefIds.length ? e.giftRefIds.join(',') : '',
                giftRefIds: e.giftRefIds,
                giftQuantity: 1,
                limitPerUser: 1,
                targetUserType: e.targetUserType.join(''),
                extraGiftRuleQuantity: e.extraGiftRuleQuantity,
                extraGiftRuleType: e.targetUserType.join('') === '0101' ? '01' : ''
            }
        }).concat(formData.extraGiftRules),
        remark: formData.remark
    }
    console.log(obj, "obj==");

    return obj
}

const addHandle = async () => {
    try {
        const res = await addActive(buildActivityObj())
        if (res.code === '00000') {
            ElMessage.success('新增成功')
        } else {
            ElMessage.error(res.msg || '新增失败')
        }
    } catch (e) {
        ElMessage.error('新增异常')
    }
}

const editHandle = async () => {
    try {
        const res = await editActive(editId.value, buildActivityObj())
        if (res.code === '00000') {
            ElMessage.success('编辑成功')
            getEditActiveData()
        } else {
            ElMessage.error(res.msg || '编辑失败')
        }
    } catch (e) {
        ElMessage.error('编辑异常')
    }
}

const getVipList = async () => {
    try {
        const res = await vipEquity({
            pageNum: 1,
            pageSize: 1000,
            queryIsVip: 1
        })
        if (res.code === '00000') {
            vipData.value = res.data.list
        }
    } catch { } finally { }
}

/**
 * 回填老用户额外赠送规则
 */
function fillExtraGiftRulesFromBack(activityContentAoList: any[]) {
    console.log(activityContentAoList, "activityContentAoList===");

    // 仅筛选 targetUserType 为 '0101' 的规则
    const extraRules = activityContentAoList
        .filter((item: any) =>
            item.targetUserType === '0101'
        )
        .map((e: any) => {
            return {
                targetType: e.targetType,
                giftType: e.giftType,
                giftRefIds: e.giftRefIds,
                // 回填数量
                giftQuantity: e.giftQuantity ?? 1,
                limitPerUser: e.limitPerUser ?? 0,
                targetUserType: (Array.isArray(e.targetUserType) ? e.targetUserType.join('') : e.targetUserType),
                extraGiftRuleQuantity: e.extraGiftRuleQuantity,
                extraGiftRuleType: e.extraGiftRuleType ?? '01'
            }
        });
    formData.extraGiftRules = extraRules;
}

const getEditActiveData = async () => {
    try {
        const res = await getActivityInfo(editId.value)
        if (res.code === '00000') {
            const data = res.data
            formData.activityName = data.activityName
            formData.shareImage = data.shareImage
            formData.receiveSuccessImage = data.receiveSuccessImage
            formData.startTime = data.startTime
            formData.endTime = data.endTime
            formData.status = data.status
            formData.title = data.title
            formData.subtitle = data.subtitle
            formData.remark = data.remark
            formData.activeTime = [data.startTime, data.endTime]

            // 重置活动内容列表
            formData.activityContentVoList = [{
                targetType: '01',
                giftType: '04',
                // giftRefIds: [],
                giftRefIds: '',
                targetUserType: ['01'],
                giftQuantity: 1,
                limitPerUser: 1,
                extraGiftRuleQuantity: 0,
                extraGiftRuleType: '01'
            },
            {
                targetType: '01',
                giftType: '04',
                // giftRefIds: [],
                giftRefIds: '',
                targetUserType: ['02'],
                giftQuantity: 1,
                limitPerUser: 0,
                extraGiftRuleQuantity: 0,
                extraGiftRuleType: '01'
            }]

            if (data.activityContentAoList && data.activityContentAoList.length > 0) {
                // 处理老用户赠送内容
                const oldUserContent = data.activityContentAoList.find((item: any) => item.targetUserType === '01')
                if (oldUserContent) {
                    // console.log(oldUserContent, "oldUserContent===");
                    formData.activityContentVoList[0] = {
                        ...formData.activityContentVoList[0],
                        ...oldUserContent,
                        // giftRefIds: oldUserContent.giftRefIds ? oldUserContent.giftRefIds.split(',') : []
                        giftRefIds: oldUserContent.giftRefIds
                    }
                    // formData.oldUserGiftType = oldUserContent.giftRefIds && oldUserContent.giftRefIds.length > 0 ? ['1'] : []
                    formData.activityContentVoList[0].targetUserType = oldUserContent.giftRefIds && oldUserContent.giftRefIds.length > 0 ? ['01'] : []
                } else {
                    // formData.oldUserGiftType = []
                    formData.activityContentVoList[0].targetUserType = []
                }
                // console.log(formData.activityContentVoList[0], "formData.activityContentVoList[0]===");

                // 处理新用户赠送内容
                const newUserContent = data.activityContentAoList.find((item: any) => item.targetUserType === '02')


                if (newUserContent) {
                    // console.log(newUserContent, "newUserContent===");

                    formData.activityContentVoList[1] = {
                        ...formData.activityContentVoList[1],
                        ...newUserContent,
                        // giftRefIds: newUserContent.giftRefIds ? newUserContent.giftRefIds.split(',') : []
                        giftRefIds: newUserContent.giftRefIds
                    }
                    // formData.newUserGiftType = newUserContent.giftRefIds && newUserContent.giftRefIds.length > 0 ? ['1'] : []
                    formData.activityContentVoList[1].targetUserType = newUserContent.giftRefIds && newUserContent.giftRefIds.length > 0 ? ['02'] : []
                } else {
                    // formData.newUserGiftType = []
                    formData.activityContentVoList[1].targetUserType = []
                }

                // 额外赠送 回显
                fillExtraGiftRulesFromBack(data.activityContentAoList);

                // 判断老用户额外赠送开关
                if (data.activityContentAoList.some((item: any) => item.targetUserType === '0101')) {
                    formData.state = 1
                } else {
                    formData.state = 0
                }
            } else {
                // 如果没有活动内容，重置赠送类型
                // formData.oldUserGiftType = []
                // formData.newUserGiftType = []
                formData.activityContentVoList[0].targetUserType = []
                formData.activityContentVoList[1].targetUserType = []
            }
            // console.log(formData.activityContentVoList, "formData.activityContentVoList===");
        }
    } catch (e) {
    } finally { }
}
onMounted(() => {
    if (route.query.id) {
        editId.value = String(route.query.id)
        getEditActiveData()
    }
    getVipList()
})

</script>
<style scoped lang="scss">
.page-content {
    width: 100%;
    height: 100%;

    .header {
        padding-bottom: 15px;
        // border-bottom: 1px solid var(--art-border-color);

        h3 {
            font-size: 18px;
            font-weight: bold;
        }
    }

    :deep(.el-form) {
        .el-form-item {
            max-width: 700px;
        }
    }
}

.tips {
    color: #333;
    font-size: 15px;
    font-weight: 500;
}

.coutomTips {
    color: #b2b4b4;
}

.check {
    color: #5f79d1;
}

:deep(.editor-wrapper) {
    z-index: 0;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;

    .mask {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 24px;
        background-color: rgba(0, 0, 0, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s ease;
        color: #fff;
        font-size: 12px;
    }

    .del-image {
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        color: #8c939d;
    }

    &:hover .mask {
        opacity: 1;
    }

    &:hover .del-image {
        display: block;
    }
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.giftRules {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    width: 500px;

    .rules {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }
}

.addRules {
    margin: 20px 0 20px 130px;
}
</style>